package com.kaibes.module.account.core;

import java.util.List;

import org.springframework.stereotype.Service;

import com.kaibes.core.base.option.NullOptions;
import com.kaibes.module.account.pojo.Account;
import com.kaibes.orm.core.core.Page;
import com.kaibes.orm.curd.Query;
import com.kaibes.orm.curd.QueryBuilder;
import com.kaibes.orm.curd.SelectBuilder;
import com.kaibes.orm.curd.UpdateBuilder;
import com.kaibes.web.api.ResponseServiceImpl;

@Service
public class AccountService extends ResponseServiceImpl<Account> {
    
	public Account getByUsername(String username) {
        return get(QueryBuilder.newBuilder().eq("username", username).build());
    }
	
	public Account getByUserId(int userId) {
        return get(query().eq("user_id", userId).build());
    }
    
    public String getUsernameById(Integer id) {
        return NullOptions.returnString(get(QueryBuilder.newBuilder().eq("id", id).build(), "username"), user->user.getUsername());
    }
    
    public String getUsernameByUserId(Integer userId) {
        return NullOptions.returnString(get(QueryBuilder.newBuilder().eq("user_id", userId).build(), "username"), user->user.getUsername());
    }
    
    public Page<Account> pageByUsernameLike(Integer current, Integer size, String search) {
        return page(current, size, QueryBuilder.newBuilder().like("username", search).build());
    }
    
    public boolean removeByUserId(List<?> userIds) {
        return remove(QueryBuilder.newBuilder().inList("user_id", userIds).build())>0;
    }
    
    public boolean updateByUserId(Object data, Integer userId) {
        return update(data, QueryBuilder.newBuilder().eq("user_id", userId).build())>0;
    }
    
    public boolean updatePasswordByUserId(String password, Integer userId) {
        return getMapper().update(UpdateBuilder.newBuilder().setValue("password", password).addQuery(QueryBuilder.newBuilder().eq("user_id", userId).build()).build())>0;
    }
    
    public boolean updatePasswordByEmail(String password, String email) {
        Query query = QueryBuilder.newBuilder().eqSelect("user_id", 
                SelectBuilder.newBuilder().setTableName("user_safe").addColumn("user_id").addQuery(
                        QueryBuilder.newBuilder().eq("email", email).build()).build()).build();
        return getMapper().update(UpdateBuilder.newBuilder().setValue("password", password).addQuery(query).build())>0;
    }
    
}
